//
//  OHttp.m
//  soccer
//
//  Created by 上官千城 on 15/9/18.
//  Copyright (c) 2015年 上官千城. All rights reserved.
//

#import "ONet.h"

@implementation ONet
-(instancetype) initWithMethod:(Method)method url:(NSString *)url params:(NSDictionary *)params reqData:(NSData *)reqData
{
    self = [super init];
    if (self) {
        _requestHeads = [NSMutableDictionary dictionary];
        _method = method;
        _url = url;
        _params = params;
        _reqData = reqData;
        return self;
    }
    return nil;
}

-(void) setCookie:(NSDictionary*) respHeads
{
    NSString* setcookie = [respHeads objectForKey:@"set-cookie"];
    if (setcookie) {
        //TODO:
        //NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
        NSArray* cookie_array = [setcookie componentsSeparatedByString:@";"];
        
        NSArray* sessionInfo = [cookie_array[0] componentsSeparatedByString:@"="];
        NSArray* pathInfo = [cookie_array[1] componentsSeparatedByString:@"="];
        
        OHttpSession* session = [OHttpSession getSession:pathInfo[1]];
        if (session == nil) {
            session = [[OHttpSession alloc] initWithSessionId:sessionInfo[1] lastTime:0 expire:0];
            [OHttpSession addSession:pathInfo[1] session:session];
        }
        else {
            session.sessionId = sessionInfo[1];
        }
        
        //TODO:session.lastTime = nsdate
    }
}

-(NSString*) getPath
{
    //TODO:通过分析_url来得到path
    NSArray *array = [_url componentsSeparatedByString:@"/"];
    NSString *str = array[3];
    NSString *path = [NSString stringWithFormat:@"/%@",str];
    return path;
}

//向http请求头中设置session
-(void) setSessionToRequestHead:(AFHTTPRequestOperationManager*)manager
{
    NSString* path = [self getPath];
    OHttpSession* session = [OHttpSession getSession:path];
    if (session) {
        //组织清求头
        //AFHTTPSessionManager
        NSString* value = [NSString stringWithFormat:@"jsessionid=%@",session.sessionId];
       
        [manager.requestSerializer setValue:value forHTTPHeaderField:@"cookie"];
    }
}

-(void) asynSend:(id<OLogicRun>)myDelegate
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [self setSessionToRequestHead:manager];
    
    if (_method == GET) {
        [manager GET:_url parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSHTTPURLResponse* response = operation.response;
            _httpCode = response.statusCode;
            if(response.statusCode != CODE_OK) {
                //TODO:
//                if (response.statusCode == USER_PWD_ERROR) {
                    //网络错误
                    UIAlertView *Signature = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [Signature show];
//                }
            }
            else {
                [self setCookie:[response allHeaderFields]];
                
                NSString* erc = [[response allHeaderFields] objectForKey:ERC];
                if (erc) {
                    _erc = [erc integerValue];
                }
                else {
                    _erc = SUCC;
                }
                
                if (_erc == SUCC) {
                    _respData = operation.responseData;
                    [myDelegate run:_respData erc:_erc];
                }
                else{
                    [myDelegate run:nil erc:_erc];
                }
            }
            _isDone = YES;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSHTTPURLResponse *response = operation.response;
            NSLog(@"%ld",response.statusCode);
            NSLog(@"%@", error);
            NSString *str = [NSString stringWithFormat:@"连接错误code = %ld",response.statusCode];
            [UIUtils showAlert:@"提示" message:str left:@"确定" right:nil delegate:nil];
            
            _isDone =YES;
        }];
    }
    else if(_method == POST){
        
    }
    else {
        //TODO:
    }
}

-(BOOL) syncSend
{
    [self asynSend:nil];
    while (YES) {
        if (_isDone) {
            break;
        }
        [NSThread sleepForTimeInterval:0.05];
    }
    if (_httpCode != CODE_OK) {
        //TODO:网络发生异常
        UIAlertView *Signature = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [Signature show];
        return NO;
    }
    return YES;
}

-(BOOL) isDone
{
    return _isDone;
}

-(Method) getMethod
{
    return _method;
}

-(NSInteger) getErc
{
    return _erc;
}

-(NSData*) getRespData
{
    return _respData;
}

@end
